package com.example.servlet.manager;

import com.example.email.EmailSender;
import com.example.entity.Flight;
import com.example.entity.Manager;
import com.example.entity.Ticket;
import com.example.service.OperationService;
import com.example.service.impl.OperationServiceImpl;
import com.example.utils.MybatisUtil;
import com.example.utils.ThymeleafUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.Context;

import java.io.Console;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@WebServlet("/manager_edit_flight")
public class mEditFlightServlet extends HttpServlet {
    private OperationService service;
    private SqlSession sqlSession;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new OperationServiceImpl(sqlSession);
    }
    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Manager manager = (Manager) req.getSession().getAttribute("manager");
        String f_id = req.getParameter("f_id");
        String numberPart = f_id.replaceAll("\\D+", ""); // 移除所有非数字字符
        int idNumber = Integer.parseInt(numberPart);
        Context context = new Context();
        context.setVariable("managername", manager.getM_name());
        context.setVariable("flight", service.getFlightWithStatus(idNumber));
        ThymeleafUtil.process("manager_flight_edit.html", context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String flightId = req.getParameter("flightId");
        String status  = req.getParameter("status");
        String gate = req.getParameter("gate");
        String departureDate = req.getParameter("departureDate");
        String arrivalDate = req.getParameter("arrivalDate");
        String departureTime = req.getParameter("departureTime");
        String arrivalTime = req.getParameter("arrivalTime");
        double distance = Double.parseDouble(req.getParameter("distance"));
        double economyPrice = Double.parseDouble(req.getParameter("economyPrice"));
        double businessPrice = Double.parseDouble(req.getParameter("businessPrice"));
        double firstPrice = Double.parseDouble(req.getParameter("firstPrice"));
        int Baggage = Integer.parseInt(req.getParameter("Baggage"));
        String mealMoney = req.getParameter("mealMoney");
        String mealType = req.getParameter("mealType");
        String captain = req.getParameter("captain");
        String assistant_captain = req.getParameter("assistant_captain");
        String chief_attendant = req.getParameter("chief_attendant");
        int flight_crew_num = Integer.parseInt(req.getParameter("flight_crew_num"));
        String numberPart = flightId.replaceAll("\\D+", ""); // 移除所有非数字字符
        int idNumber = Integer.parseInt(numberPart);
        try{
            if(service.editFlight(idNumber, gate, departureDate, arrivalDate, departureTime, arrivalTime, distance, economyPrice, businessPrice, firstPrice, Baggage, mealMoney, mealType)==0){
                throw new Exception("Failed to edit flight");
            }
            if(service.editFlightStatus(idNumber, status, captain, assistant_captain, chief_attendant, flight_crew_num)==0){
                throw new Exception("Failed to edit flightStatus");
            }
            service.commit();
            req.getSession().setAttribute("edit_success", new Object());
            List<Ticket> tickets = service.getTicketsByFlightId(idNumber);
            for (Ticket ticket : tickets) {
                if(Objects.equals(ticket.getStatusText(), "已取消")) continue;
                String email = service.getEmailByPassengerId(ticket.getPassenger_id());
                if (email != null && !email.isEmpty()) {
                    EmailSender.sendFlightUpdatedNotification(email, flightId); // 调用发送邮件方法
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            service.rollback();
            req.getSession().setAttribute("edit_failure", new Object());
            resp.sendRedirect("manager_flight");
        }
        resp.sendRedirect("manager_flight");
    }
}
